package com.kotlin.hxh.adapter

import android.graphics.Color
import androidx.recyclerview.widget.RecyclerView
import android.util.SparseBooleanArray
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.kotlin.hxh.R
import com.kotlin.hxh.listener.OnItemClickListener
import java.util.*

/**
 * @author huxh
 * @date 2018/12/20.
 */
class MenuAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<RecyclerViewHolder>() {

    private val mitems = ArrayList<String>()

    private var mLastCheckedPosition = -1
    private lateinit var mBooleanArray: SparseBooleanArray

    override fun onCreateViewHolder(p0: ViewGroup, p1: Int) = RecyclerViewHolder.createViewHolder(p0.context, p0, R.layout.item_menu)

    override fun getItemCount() = mitems.size

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
        val tvName = holder.getView<TextView>(R.id.tv_name)
        holder.itemView.setOnClickListener { clickListener?.onItemClick(holder.adapterPosition, it, holder) }
        if (!mBooleanArray[position]) {
            holder.getView2(R.id.view_line).visibility = View.INVISIBLE
            holder.itemView.setBackgroundResource(R.color.bg_app)
            tvName.setTextColor(Color.BLACK)
        } else {
            tvName.setTextColor(holder.context.resources.getColor(R.color.colorAccent))
            holder.getView2(R.id.view_line).visibility = View.VISIBLE
            holder.itemView.setBackgroundColor(Color.WHITE)
        }
        tvName.text = mitems[position]
    }

    fun setDatas(items: List<String>) {
        mitems.clear()
        mitems.addAll(items)
        mBooleanArray = SparseBooleanArray(mitems.size)
    }

    fun setItemChecked(position: Int) {
        mBooleanArray.put(position, true)
        if (mLastCheckedPosition > -1) {
            mBooleanArray.put(mLastCheckedPosition, false)
            notifyItemChanged(mLastCheckedPosition)
        }
        notifyDataSetChanged()
        mLastCheckedPosition = position
    }

    private var clickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.clickListener = listener
    }
}